

package cn.shengchao.examstart.user.acl.adapters.client;

import cn.hutool.core.util.RandomUtil;
import cn.shengchao.examstart.user.acl.adapters.client.cloudauth20190307.Client;
import cn.shengchao.examstart.user.acl.adapters.client.cloudauth20190307.models.ContrastFaceVerifyAdvanceRequest;
import cn.shengchao.examstart.user.acl.adapters.client.cloudauth20190307.models.ContrastFaceVerifyResponse;
import cn.shengchao.examstart.user.acl.ports.client.IRealPersonAuthenticationApi;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

@Service
public class AliRealPersonAuthenticationApi implements IRealPersonAuthenticationApi {
    @Override
    public ContrastFaceVerifyResponse contrastFaceVerify(String userId,
                                                         String name,
                                                         String idcard,
                                                         InputStream realPersonVideo) {
        // 通过以下代码创建API请求并设置参数。
        ContrastFaceVerifyAdvanceRequest request = new ContrastFaceVerifyAdvanceRequest();
        // 请输入场景ID+L。
        request.setSceneId(1000012129L);
        request.setOuterOrderNo(RandomUtil.randomNumbers(12));
        request.setProductCode("ID_MIN_VIDEO");
        // 卡证核身类型，固定值。
        request.setModel("FRONT_CAMERA_LIVENESS");
        // 证件类型，固定值。
        request.setCertType("IDENTITY_CARD");
        request.setCertName(name);
        request.setCertNo(idcard);
        request.setUserId(userId);
        // 设置本地文件路径。
        request.setFaceContrastFileObject(realPersonVideo);
        // 推荐，支持服务路由。
        // 不支持服务自动路由。
        //ContrastFaceVerifyResponse response = contrastFaceVerify("cloudauth.cn-shanghai.aliyuncs.com", request);
        return contrastFaceVerifyAutoRoute(request);
    }

    private static ContrastFaceVerifyResponse contrastFaceVerifyAutoRoute(ContrastFaceVerifyAdvanceRequest request) {
        // 第一个为主区域Endpoint，第二个为备区域Endpoint。
        List<String> endpoints = Arrays
            .asList("cloudauth.cn-shanghai.aliyuncs.com", "cloudauth.cn-beijing.aliyuncs.com");
        ContrastFaceVerifyResponse lastResponse = null;
        for (int i = 0; i < endpoints.size(); i++) {
            try {
                ContrastFaceVerifyResponse response = contrastFaceVerify(endpoints.get(i), request);
                lastResponse = response;

                // 服务端错误，切换到下个区域调用。
                if (response != null) {
                    if (500 == response.getStatusCode()) {
                        continue;
                    }
                    if (response.getBody() != null) {
                        if ("500".equals(response.getBody().getCode())) {
                            continue;
                        }
                    }
                }

                return response;
            } catch (Exception e) {
                e.printStackTrace();
                if (i == endpoints.size() - 1) {
                    throw new RuntimeException(e);
                }
            }
        }

        return lastResponse;
    }

    private static ContrastFaceVerifyResponse contrastFaceVerify(String endpoint,
                                                                 ContrastFaceVerifyAdvanceRequest request) throws Exception {
        // 阿里云账号AccessKey拥有所有API的访问权限，建议您使用RAM用户进行API访问或日常运维。
        // 强烈建议不要把AccessKey ID和AccessKey Secret保存到工程代码里，否则可能导致AccessKey泄露，威胁您账号下所有资源的安全。
        //本示例通过阿里云Credentials工具从环境变量中读取AccessKey，来实现API访问的身份验证。如何配置环境变量，请参见https://help.aliyun.com/document_detail/378657.html。
        Config config = new Config();
        config.setEndpoint(endpoint);
        config.setAccessKeyId("LTAIBabaYDfy5oiy");
        config.setAccessKeySecret("tn987BbDeppXLp7mthEwniFVC9FhQh");
        // 设置http代理。
        //config.setHttpProxy("http://xx.xx.xx.xx:xxxx");
        // 设置https代理。
        //config.setHttpsProxy("http://xx.xx.xx.xx:xxxx");
        Client client = new Client(config);

        // 创建RuntimeObject实例并设置运行参数。
        RuntimeOptions runtime = new RuntimeOptions();
        runtime.readTimeout = 10000;
        runtime.connectTimeout = 10000;
        return client.contrastFaceVerifyAdvance(request, runtime);
    }
}
